// 获取订单列表
async function getOrders() {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            window.location.href = 'login.html';
            return;
        }

        const response = await fetch('/api/orders/', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        const orders = await response.json();
        displayOrders(orders);
    } catch (error) {
        console.error('Error:', error);
        alert('获取订单列表失败');
    }
}

// 显示订单列表
function displayOrders(orders) {
    const orderList = document.querySelector('.order-list');
    orderList.innerHTML = '';

    orders.forEach(order => {
        const orderItem = document.createElement('div');
        orderItem.className = 'order-item';
        orderItem.innerHTML = `
            <h3>订单号: ${order.id}</h3>
            <p>餐厅: ${order.restaurant.name}</p>
            <p>状态: ${getStatusText(order.status)}</p>
            <p>总金额: ￥${order.total_amount}</p>
            <p>配送地址: ${order.delivery_address}</p>
            <p>创建时间: ${new Date(order.created_at).toLocaleString()}</p>
            <div class="order-actions">
                ${getOrderActions(order)}
            </div>
        `;
        orderList.appendChild(orderItem);
    });
}

// 获取订单状态中文描述
function getStatusText(status) {
    const statusMap = {
        'pending': '待支付',
        'paid': '已支付',
        'preparing': '准备中',
        'delivering': '配送中',
        'completed': '已完成',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}

// 根据订单状态获取可用操作
function getOrderActions(order) {
    let actions = '';
    
    switch(order.status) {
        case 'pending':
            actions = `
                <button class="btn" onclick="payOrder(${order.id})">立即支付</button>
                <button class="btn" onclick="cancelOrder(${order.id})">取消订单</button>
            `;
            break;
        case 'completed':
            if (!order.reviewed) {
                actions = `<button class="btn" onclick="reviewOrder(${order.id})">评价订单</button>`;
            }
            break;
        case 'delivering':
            actions = `<button class="btn" onclick="confirmReceived(${order.id})">确认收货</button>`;
            break;
    }
    
    return actions;
}

// 支付订单
async function payOrder(orderId) {
    try {
        const token = localStorage.getItem('token');
        const response = await fetch(`/api/orders/${orderId}/pay/`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            alert('支付成功！');
            getOrders(); // 刷新订单列表
        } else {
            alert('支付失败，请稍后重试');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('支付失败，请稍后重试');
    }
}

// 取消订单
async function cancelOrder(orderId) {
    if (!confirm('确定要取消该订单吗？')) {
        return;
    }

    try {
        const token = localStorage.getItem('token');
        const response = await fetch(`/api/orders/${orderId}/cancel/`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            alert('订单已取消');
            getOrders(); // 刷新订单列表
        } else {
            alert('取消订单失败，请稍后重试');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('取消订单失败，请稍后重试');
    }
}

// 确认收货
async function confirmReceived(orderId) {
    try {
        const token = localStorage.getItem('token');
        const response = await fetch(`/api/orders/${orderId}/confirm/`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            alert('已确认收货');
            getOrders(); // 刷新订单列表
        } else {
            alert('确认收货失败，请稍后重试');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('确认收货失败，请稍后重试');
    }
}

// 评价订单
function reviewOrder(orderId) {
    // 跳转到评价页面
    window.location.href = `review.html?orderId=${orderId}`;
}

// 监听状态筛选变化
document.getElementById('statusFilter').addEventListener('change', function() {
    const status = this.value;
    const token = localStorage.getItem('token');
    
    fetch(`/api/orders/?status=${status}`, {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
        .then(response => response.json())
        .then(orders => displayOrders(orders))
        .catch(error => {
            console.error('Error:', error);
            alert('获取订单列表失败');
        });
});

// 页面加载时获取订单列表
document.addEventListener('DOMContentLoaded', getOrders);
